﻿using System.Diagnostics.Contracts;

namespace Hippo.Console.Lib
{
    using System;
    using System.Collections.Specialized;
    using Hippo.Common;

    public class ConsoleConfigurationProfile : IConfigurationProfile
    {
        public const string ReportsPathIdentifier = "reportsPath";
        public const string WaitForAgentsIdentifier = "waitForAgents";
        public const string WaitTimeoutIdentifier = "waitTimeout";

        private const int WaitTimeoutDefaultValue = 60;

        private readonly NameValueCollection settings;

        public ConsoleConfigurationProfile()
            : this(new NameValueCollection())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConsoleConfigurationProfile"/> class.
        /// </summary>
        /// <param name="settings">Use the AppSettings here.</param>
        public ConsoleConfigurationProfile(NameValueCollection settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            Contract.EndContractBlock();

            this.settings = settings;
        }

        public string ReportsPath
        {
            get { return settings[ReportsPathIdentifier] ?? string.Empty; }
        }

        public string[] WaitForAgents
        {
            get
            {
                if (settings[WaitForAgentsIdentifier] != null)
                {
                    return settings[WaitForAgentsIdentifier].Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
                }

                return new[] {Environment.MachineName};
            }
        }

        public TimeSpan WaitTimeout
        {
            get
            {
                if (settings[WaitTimeoutIdentifier] != null)
                {
                    return TimeSpan.FromSeconds(int.Parse(settings[WaitTimeoutIdentifier]));
                }

                return TimeSpan.FromSeconds(WaitTimeoutDefaultValue);
            }
        }

        public void Set(string name, string value)
        {
            settings.Set(name, value);
        }

        public string Get(string key)
        {
            return settings[key];
        }
    }
}
